package com.gitee.mocoffee.log.spring;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StreamUtils;
import org.springframework.web.util.ContentCachingResponseWrapper;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogRequestFilter implements Filter {
    private static class BodyRepeatableServletRequestWrapper extends HttpServletRequestWrapper {
        private final byte[] body;

        private BodyRepeatableServletRequestWrapper(HttpServletRequest request) throws IOException {
            super(request);
            body = StreamUtils.copyToByteArray(request.getInputStream());
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream bais = new ByteArrayInputStream(body);
            return new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return true;
                }

                @Override
                public void setReadListener(ReadListener readListener) {
                }

                @Override
                public int read() throws IOException {
                    return bais.read();
                }
            };
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        BodyRepeatableServletRequestWrapper request = new BodyRepeatableServletRequestWrapper(
                (HttpServletRequest) servletRequest);
        ContentCachingResponseWrapper response = new ContentCachingResponseWrapper(
                (HttpServletResponse) servletResponse);

        String uri = request.getRequestURI();

        boolean hasParameter = false;
        StringBuilder params = new StringBuilder("[");
        String body = null;

        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            hasParameter = true;
            String name = paramNames.nextElement();
            String value = request.getParameter(name);
            params.append(name).append('=').append(value).append('&');
        }
        if (hasParameter) {
            params.deleteCharAt(params.length() - 1);
        }
        params.append(']');

        if (!hasParameter) {
            String encoding = request.getCharacterEncoding();
            if (StringUtil.isBlank(encoding)) {
                encoding = "utf-8";
            }
            body = StreamUtils.copyToString(request.getInputStream(), Charset.forName(encoding));
        }

        log.info("path {} requestParam: {}, requestBody: {}", uri, params.toString(), body);

        long start = System.currentTimeMillis();
        try {
            filterChain.doFilter(request, response);
        } finally {
            String res = null;
            byte[] bodyBytes = response.getContentAsByteArray();
            response.copyBodyToResponse();
            if (bodyBytes != null && bodyBytes.length > 0) {
                res = new String(bodyBytes, StandardCharsets.UTF_8);
            }
            long end = System.currentTimeMillis();
            log.info("elapse {} ms, with response: {}", (end - start), res);
        }
    }

    @Override
    public void destroy() {
    }
}
